<template>
  <div class="doctor-intro">
    <page-header title="医院简介" subtitle="了解我院的历史、文化和特色科室"></page-header>
    
    <el-card class="intro-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>医院概况</span>
        </div>
      </template>
      
      <div class="hospital-overview">
        <div class="hospital-image">
          <el-image
            style="width: 100%; height: 300px"
            src="https://via.placeholder.com/800x300"
            fit="cover"
            :preview-src-list="['https://via.placeholder.com/800x300']"
          ></el-image>
        </div>
        <div class="hospital-description">
          <h3>{{ hospitalInfo.name }}</h3>
          <p>{{ hospitalInfo.description }}</p>
          
          <el-row :gutter="20" class="hospital-stats">
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-number">{{ hospitalInfo.foundYear }}</div>
                <div class="stat-label">创建年份</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-number">{{ hospitalInfo.bedCount }}</div>
                <div class="stat-label">开放床位</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-number">{{ hospitalInfo.staffCount }}+</div>
                <div class="stat-label">医护人员</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-item">
                <div class="stat-number">{{ hospitalInfo.deptCount }}+</div>
                <div class="stat-label">临床科室</div>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-card>
    
    <el-card class="intro-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>特色科室</span>
        </div>
      </template>
      
      <el-tabs tab-position="left" class="department-tabs">
        <el-tab-pane v-for="dept in departments" :key="dept.id" :label="dept.name">
          <div class="department-detail">
            <div class="department-header">
              <h3>{{ dept.name }}</h3>
              <p>{{ dept.description }}</p>
            </div>
            
            <el-divider content-position="center">科室专家</el-divider>
            
            <el-row :gutter="20">
              <el-col :span="8" v-for="doctor in dept.doctors" :key="doctor.id">
                <el-card shadow="hover" class="doctor-card">
                  <div class="doctor-info">
                    <el-avatar :size="80" :src="doctor.avatar"></el-avatar>
                    <h4>{{ doctor.name }}</h4>
                    <p class="doctor-title">{{ doctor.title }}</p>
                    <p class="doctor-specialty">擅长：{{ doctor.specialty }}</p>
                    <el-button type="primary" size="small" @click="goToAppointment(dept.id, doctor.id)">
                      预约挂号
                    </el-button>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    
    <el-card class="intro-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>医院荣誉</span>
        </div>
      </template>
      
      <el-timeline>
        <el-timeline-item
          v-for="(award, index) in awards"
          :key="index"
          :timestamp="award.year"
          placement="top"
          :type="award.type"
          :hollow="award.hollow"
        >
          {{ award.title }}
        </el-timeline-item>
      </el-timeline>
    </el-card>
    
    <el-card class="intro-card">
      <template #header>
        <div class="card-header">
          <span>联系我们</span>
        </div>
      </template>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="contact-info">
            <h3>联系方式</h3>
            <p><el-icon><Location /></el-icon> 地址：{{ hospitalInfo.address }}</p>
            <p><el-icon><Phone /></el-icon> 电话：{{ hospitalInfo.phone }}</p>
            <p><el-icon><Message /></el-icon> 邮箱：{{ hospitalInfo.email }}</p>
            <p><el-icon><Clock /></el-icon> 门诊时间：{{ hospitalInfo.officeHours }}</p>
            <p><el-icon><Service /></el-icon> 急诊电话：{{ hospitalInfo.emergencyPhone }}</p>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="map-container">
            <div class="map-placeholder">
              <p>这里将显示医院地图</p>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import PageHeader from '@/components/PageHeader.vue'
import { Location, Phone, Message, Clock, Service } from '@element-plus/icons-vue'
import { getHospital } from '@/api/hospital'
import { listDepartment } from '@/api/department'
import { listDoctor } from '@/api/doctor'
import { listAward } from '@/api/award'
import { ElMessage } from 'element-plus'

const router = useRouter()
const loading = ref(false)
const departments = ref([])
const awards = ref([])
const hospitalInfo = ref({
  name: '',
  foundYear: '',
  bedCount: 0,
  staffCount: 0,
  deptCount: 0,
  description: '',
  address: '',
  phone: '',
  email: '',
  officeHours: '',
  emergencyPhone: ''
})

// 获取医院信息
const fetchHospitalInfo = async () => {
  loading.value = true
  
  try {
    // 默认获取ID为1的医院信息
    const res = await getHospital(1)
    if (res.code === 200) {
      const data = res.data
      if (data) {
        hospitalInfo.value = {
          name: data.name || 'XX医院',
          foundYear: data.foundYear || '1950',
          bedCount: data.bedCount || 1200,
          staffCount: data.staffCount || 2000,
          deptCount: data.deptCount || 30,
          description: data.description || 'XX医院创建于1950年，是一所集医疗、教学、科研、预防、保健、康复为一体的综合性三级甲等医院。',
          address: data.address || 'XX市XX区XX路XX号',
          phone: data.phone || '0123-4567890',
          email: data.email || 'hospital@example.com',
          officeHours: data.officeHours || '周一至周五 8:00-17:30，周六周日 8:00-12:00',
          emergencyPhone: data.emergencyPhone || '120'
        }
      }
    } else {
      ElMessage.error(res.msg || '获取医院信息失败')
      // 设置默认数据
      setDefaultHospitalInfo()
    }
  } catch (error) {
    console.error('获取医院信息失败', error)
    ElMessage.error('获取医院信息失败')
    // 设置默认数据
    setDefaultHospitalInfo()
  } finally {
    loading.value = false
  }
}

// 设置默认医院信息
const setDefaultHospitalInfo = () => {
  hospitalInfo.value = {
    name: 'XX医院',
    foundYear: '1950',
    bedCount: 1200,
    staffCount: 2000,
    deptCount: 30,
    description: 'XX医院创建于1950年，是一所集医疗、教学、科研、预防、保健、康复为一体的综合性三级甲等医院。医院占地面积约10万平方米，建筑面积8万平方米，开放床位1200张。医院现有职工2000余人，其中高级职称300余人，博士、硕士研究生500余人。医院设有临床科室30个，医技科室10个，专科研究所5个。医院秉承"以人为本，救死扶伤"的宗旨，坚持"科技兴院，人才强院"的发展战略，努力为患者提供高质量的医疗服务。',
    address: 'XX市XX区XX路XX号',
    phone: '0123-4567890',
    email: 'hospital@example.com',
    officeHours: '周一至周五 8:00-17:30，周六周日 8:00-12:00',
    emergencyPhone: '120'
  }
}

// 获取科室及医生信息
const fetchDepartments = async () => {
  loading.value = true
  
  try {
    // 获取特色科室
    const res = await listDepartment({ isFeatured: true })
    if (res.code === 200) {
      const deptList = res.data || []
      
      // 如果没有数据，使用默认数据
      if (deptList.length === 0) {
        setDefaultDepartments()
        return
      }
      
      // 先保存科室信息
      departments.value = deptList.map(dept => ({
        id: dept.id,
        name: dept.name,
        description: dept.description,
        doctors: []
      }))
      
      // 然后为每个科室获取医生信息
      const promises = departments.value.map(async dept => {
        try {
          const doctorRes = await listDoctor({ departmentId: dept.id })
          if (doctorRes.code === 200) {
            const doctors = doctorRes.data || []
            
            // 更新科室中的医生列表
            const deptIndex = departments.value.findIndex(d => d.id === dept.id)
            if (deptIndex !== -1) {
              departments.value[deptIndex].doctors = doctors.map(doctor => ({
                id: doctor.id,
                name: doctor.name,
                title: doctor.title,
                specialty: doctor.specialty,
                avatar: doctor.avatar || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
              }))
            }
          }
        } catch (error) {
          console.error(`获取科室 ${dept.id} 的医生列表失败`, error)
        }
      })
      
      // 等待所有请求完成
      await Promise.all(promises)
    } else {
      ElMessage.error(res.msg || '获取科室列表失败')
      setDefaultDepartments()
    }
  } catch (error) {
    console.error('获取科室列表失败', error)
    ElMessage.error('获取科室列表失败')
    setDefaultDepartments()
  } finally {
    loading.value = false
  }
}

// 设置默认科室数据
const setDefaultDepartments = () => {
  departments.value = [
    {
      id: 'dept1',
      name: '内科',
      description: '内科是临床医学的一个专科，内科学是研究内脏疾病（如心脏病、肺病、肝病等）的病因、病理、诊断及治疗的一门学科。',
      doctors: [
        {
          id: 'doc1',
          name: '张医生',
          title: '主任医师',
          specialty: '心血管疾病',
          avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
        },
        {
          id: 'doc2',
          name: '李医生',
          title: '副主任医师',
          specialty: '消化系统疾病',
          avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
        },
        {
          id: 'doc3',
          name: '王医生',
          title: '主治医师',
          specialty: '呼吸系统疾病',
          avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
        }
      ]
    },
    {
      id: 'dept2',
      name: '外科',
      description: '外科是研究外科疾病的发生、发展规律及其临床表现，诊断、预防和治疗的临床学科。主要通过手术治疗疾病。',
      doctors: [
        {
          id: 'doc4',
          name: '赵医生',
          title: '主任医师',
          specialty: '普通外科',
          avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
        },
        {
          id: 'doc5',
          name: '钱医生',
          title: '副主任医师',
          specialty: '骨科',
          avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
        }
      ]
    },
    {
      id: 'dept3',
      name: '儿科',
      description: '儿科是专门研究儿童时期身心发育、疾病防治的医学专科，主要诊治儿童的各种疾病。',
      doctors: [
        {
          id: 'doc6',
          name: '孙医生',
          title: '主任医师',
          specialty: '儿童内科',
          avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
        },
        {
          id: 'doc7',
          name: '周医生',
          title: '副主任医师',
          specialty: '儿童外科',
          avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
        }
      ]
    }
  ]
}

// 获取医院荣誉
const fetchAwards = async () => {
  loading.value = true
  
  try {
    const res = await listAward({ type: 'hospital' })
    if (res.code === 200) {
      const awardList = res.data || []
      
      // 如果没有数据，使用默认数据
      if (awardList.length === 0) {
        setDefaultAwards()
        return
      }
      
      // 转换数据格式
      awards.value = awardList.map(award => {
        const year = award.awardDate ? award.awardDate.substring(0, 4) : '2022'
        let type = 'primary'
        
        // 根据奖项重要性设置不同颜色
        if (award.importance === 'high') {
          type = 'success'
        } else if (award.importance === 'medium') {
          type = 'primary'
        } else {
          type = 'warning'
        }
        
        return {
          year: year,
          title: award.name,
          type: type,
          hollow: Math.random() > 0.5 // 随机设置hollow属性
        }
      })
      
      // 按年份排序，最新的放在前面
      awards.value.sort((a, b) => b.year - a.year)
    } else {
      ElMessage.error(res.msg || '获取医院荣誉失败')
      setDefaultAwards()
    }
  } catch (error) {
    console.error('获取医院荣誉失败', error)
    ElMessage.error('获取医院荣誉失败')
    setDefaultAwards()
  } finally {
    loading.value = false
  }
}

// 设置默认荣誉数据
const setDefaultAwards = () => {
  awards.value = [
    { year: '2022', title: '全国优秀医疗机构', type: 'success', hollow: false },
    { year: '2020', title: '省级文明单位', type: 'primary', hollow: false },
    { year: '2018', title: '市级医疗质量先进单位', type: 'primary', hollow: true },
    { year: '2015', title: '全国百姓放心医院', type: 'success', hollow: true },
    { year: '2010', title: '省级三甲医院', type: 'warning', hollow: false }
  ]
}

// 页面加载时获取数据
onMounted(async () => {
  await fetchHospitalInfo()
  await fetchDepartments()
  await fetchAwards()
})

const goToAppointment = (deptId, doctorId) => {
  router.push({
    path: '/user/appointment',
    query: { deptId, doctorId }
  })
}
</script>

<style scoped>
.doctor-intro {
  padding: 20px;
}

.intro-card {
  margin-bottom: 30px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.hospital-overview {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.hospital-description h3 {
  font-size: 24px;
  margin-bottom: 15px;
}

.hospital-description p {
  line-height: 1.6;
  margin-bottom: 10px;
}

.hospital-stats {
  margin-top: 30px;
}

.stat-item {
  text-align: center;
  padding: 15px;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  color: #606266;
}

.department-tabs {
  min-height: 400px;
}

.department-header {
  margin-bottom: 20px;
}

.department-header h3 {
  font-size: 20px;
  margin-bottom: 10px;
}

.doctor-card {
  margin-bottom: 20px;
  height: 250px;
}

.doctor-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.doctor-info h4 {
  margin: 10px 0 5px;
  font-size: 16px;
}

.doctor-title, .doctor-specialty {
  margin: 5px 0;
  color: #606266;
  font-size: 14px;
}

.contact-info {
  padding: 20px;
}

.contact-info h3 {
  font-size: 18px;
  margin-bottom: 15px;
}

.contact-info p {
  margin: 10px 0;
  display: flex;
  align-items: center;
  gap: 10px;
}

.map-container {
  height: 300px;
}

.map-placeholder {
  height: 100%;
  background-color: #f5f7fa;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 4px;
}

@media (min-width: 768px) {
  .hospital-overview {
    flex-direction: row;
  }
  
  .hospital-image {
    flex: 1;
  }
  
  .hospital-description {
    flex: 1;
    padding-left: 30px;
  }
}
</style> 